package com.new4net.exe_stream.instruction.impl;

import com.new4net.exe_stream.meta.ExecutionContext;

import java.util.function.BiFunction;
import java.util.function.Function;

public class ThenInstruction<R> extends AbstractInstruction {
    private Function<ExecutionContext.InstructionContext, R> thenFunction;

    public ThenInstruction(String instructionName, Function<ExecutionContext.InstructionContext, R> thenFunction) {
        super(instructionName);
        this.instructionName = instructionName;
        this.thenFunction = thenFunction;
    }

    BiFunction<Throwable, ExecutionContext.InstructionContext, R> cathFunction;

    public void setCathFunction(BiFunction<Throwable, ExecutionContext.InstructionContext, R> cathFunction) {
        this.cathFunction = cathFunction;
    }



    @Override
    protected void exe() {
        try {
            step(":正常步骤:");
            retVal = this.thenFunction.apply(instructionContext);
        } catch (Throwable e) {
            step(":异常步骤:"+e.getMessage());
            if (cathFunction != null) {
                retVal = cathFunction.apply(e, instructionContext);

            }else {
                throw e;
            }

        }
    }


    @Override
    public String getInstuctionType() {
        return "then";
    }
}
